﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Extensions
{
	using System.Drawing;
	using System.IO;
	using System.Text.RegularExpressions;
	using System.Web;

	public static class FileExtension
	{
		/// <summary>
		/// Determines whether the specified file is a image.
		/// </summary>
		/// <param name="file">The file.</param>
		/// <returns>
		/// 	<c>true</c> if the specified file is a image; otherwise, <c>false</c>.
		/// </returns>
		public static bool IsImage(this HttpPostedFileBase file)
		{
			var regex = new Regex(@"image/\S+", RegexOptions.Compiled | RegexOptions.IgnoreCase);

			if (regex.IsMatch(file.ContentType))
			{
				try
				{
					using (var image = Image.FromStream(file.InputStream))
					{
						file.InputStream.Seek(0L, SeekOrigin.Begin);

						image.Dispose();

						return true;
					}
				}
				catch
				{
					return false;
				}
			}

			return false;
		}

		/// <summary>
		/// Gets the image dimensions for the specified file.
		/// </summary>
		/// <param name="file">The file.</param>
		/// <returns></returns>
		public static int[] GetImageDimensions(this HttpPostedFileBase file)
		{
			if (!file.IsImage())
			{
				return new[] { 0, 0 };
			}

			using (var image = Image.FromStream(file.InputStream))
			{
				return new[] { image.Width, image.Height };
			}
		}
	}
}